﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using PalFramework.Manager;

namespace PalBattleEmulator.Manager.Resource
{
    public class FrameImageManager : IManager
    {
        protected string imageDirectory;
        protected string imageFileFormat;
        protected bool preload;

        protected Dictionary<string, ImageSource> images;

        public FrameImageManager(string directory, string fileFormat, bool preload)
        {
            this.imageDirectory = directory;
            this.imageFileFormat = fileFormat;
            this.preload = preload;
        }

        protected BitmapSource loadImage(string key)
        {
            try
            {
                string path = Path.Combine(GlobalConfig.PATH_RESOURCE, imageDirectory);
                string fileName = key + "." + imageFileFormat;
                path = Path.Combine(path, fileName);
                if (!File.Exists(path)) return null;
                return loadImage(key, path);
            }
            catch (Exception ex)
            {
                Debug.Debug.Write(ex.ToString());
                return null;
            }
        }

        #region IManager 成员

        public void Initialize()
        {
            images = new Dictionary<string, ImageSource>();
            if (preload)
            {
                loadAllImages();
            }
        }

        #endregion

        private BitmapSource loadImage(string key, string filePath)
        {
            FileStream stream = File.Open(filePath, FileMode.Open);
            BitmapFrame image = BitmapFrame.Create(stream);
            CachedBitmap cachedImage = new CachedBitmap(image, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            images.Add(key, cachedImage);
            stream.Close();
            return cachedImage;
        }

        protected void loadAllImages()
        {
            try
            {
                string path = Path.Combine(GlobalConfig.PATH_RESOURCE, imageDirectory);
                DirectoryInfo directory = new DirectoryInfo(path);
                FileInfo[] files = directory.GetFiles("*." + imageFileFormat);
                foreach (FileInfo file in files)
                {
                    string fileName = file.Name.Substring(0, file.Name.LastIndexOf('.'));
                    loadImage(fileName, file.FullName);
                }
            }
            catch (IOException ex)
            {
                Debug.Debug.Write(ex.ToString());
            }
        }

        
    }
}
